#include "pomodorotimer.h"
#include "ui_pomodorotimer.h"
#include <QCloseEvent>
#include <QTimer>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QSettings>
#include <QMenu>
#include <QAction>
#include <QDate>
#include <QTextCharFormat>

PomodoroTimer::PomodoroTimer(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::PomodoroTimer)
{
    ui->setupUi(this);

    // 初始化成员变量
    timer = new QTimer(this);
    remaining = 25 * 60; // 初始25分钟
    currentPhase = Work;
    totalTomatoes = 0;
    totalMinutes = 0;
    completedCycles = 0;

    // 连接信号槽
    connect(ui->btnStartStop, &QPushButton::clicked, this, &PomodoroTimer::onStartStopClicked);
    connect(timer, &QTimer::timeout, this, &PomodoroTimer::updateTimer);

    // 初始化系统托盘和加载数据
    setupTrayIcon();
    loadData();
    updateDisplay();
}

PomodoroTimer::~PomodoroTimer()
{
  if(trayIcon) {
          trayIcon->hide();  // 确保隐藏托盘图标
          delete trayIcon;   // 显式释放内存
  }
    delete ui;
}

// 开始/停止按钮点击槽函数
void PomodoroTimer::onStartStopClicked()
{
    if(timer->isActive()) {
        timer->stop();
        ui->btnStartStop->setText("开始");
    } else {
        startCycle();
        ui->btnStartStop->setText("停止");
    }
}

// 初始化系统托盘
void PomodoroTimer::setupTrayIcon()
{
    trayIcon = new QSystemTrayIcon(QIcon(":/icon.ico"), this);

    QMenu *trayMenu = new QMenu(this);
    QAction *restoreAction = new QAction("打开主界面", this);
    QAction *quitAction = new QAction("退出", this);


     // 修改信号连接
       connect(quitAction, &QAction::triggered, this, [this](){
               m_forceQuit = true;
              close();  // 触发closeEvent
            });


    connect(restoreAction, &QAction::triggered, this, &QWidget::showNormal);
    connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);

    trayMenu->addAction(restoreAction);
    trayMenu->addSeparator();
    trayMenu->addAction(quitAction);

    trayIcon->setContextMenu(trayMenu);
    trayIcon->show();
}

// 显示系统通知
void PomodoroTimer::showNotification(const QString &message)
{
    // 添加Windows系统下的提示修复


    trayIcon->showMessage("番茄钟", message, QSystemTrayIcon::Information, 3000);

}

// 开始工作周期
void PomodoroTimer::startCycle()
{
    remaining = (currentPhase == Work) ? 25 * 60 :
                    (currentPhase == ShortBreak) ? 5 * 60 : 15 * 60;

    timer->start(1000);
    updateDisplay();
}


// 工作时间处理
void PomodoroTimer::workPhase()
{
    currentPhase = Work;
    startCycle();
    showNotification("开始专注工作！");
}

// 短休息处理
void PomodoroTimer::shortBreak()
{
    currentPhase = ShortBreak;
    startCycle();
    showNotification("开始短休息（5分钟）");
}

// 长休息处理
void PomodoroTimer::longBreak()
{
    currentPhase = LongBreak;
    startCycle();
    showNotification("开始长休息（15分钟）");
}

// 定时器更新
void PomodoroTimer::updateTimer()
{
    remaining--;

    if(remaining <= 0) {
        timer->stop();
        handlePhaseEnd();
    }

    updateDisplay();
}

// 阶段结束处理
void PomodoroTimer::handlePhaseEnd()
{
    if(currentPhase == Work) {
        totalTomatoes++;
        totalMinutes += 25;
        completedCycles++;

        QDate today = QDate::currentDate();
        dailyData[today] = dailyData.value(today, 0) + 1;

        if(completedCycles % 4 == 0) {
            longBreak();
        } else {
            shortBreak();
        }
    } else {
        workPhase();
    }

    saveDailyData();
}

// 保存每日数据
void PomodoroTimer::saveDailyData()
{
    QSettings settings("MyCompany", "PomodoroTimer");
    settings.beginWriteArray("dailyData");

    int i = 0;
    QMapIterator<QDate, int> it(dailyData);
    while (it.hasNext()) {
        it.next();
        settings.setArrayIndex(i);
        settings.setValue("date", it.key());
        settings.setValue("count", it.value());
        i++;
    }

    settings.endArray();
    settings.setValue("totalMinutes", totalMinutes);
    settings.setValue("totalTomatoes", totalTomatoes);
}

// 加载历史数据
void PomodoroTimer::loadData()
{
    QSettings settings("MyCompany", "PomodoroTimer");

    int size = settings.beginReadArray("dailyData");
    for(int i = 0; i < size; ++i) {
        settings.setArrayIndex(i);
        QDate date = settings.value("date").toDate();
        int count = settings.value("count").toInt();
        dailyData[date] = count;
    }
    settings.endArray();

    totalMinutes = settings.value("totalMinutes", 0).toInt();
    totalTomatoes = settings.value("totalTomatoes", 0).toInt();
}
void PomodoroTimer::closeEvent(QCloseEvent *event)
{
    if(m_forceQuit) {
        event->accept();    // 接受退出
    } else {
        hide();             // 隐藏窗口
        event->ignore();    // 阻止关闭

        // 可选：显示托盘提示
        trayIcon->showMessage(
            "番茄钟",
            "程序已最小化到系统托盘",
            QSystemTrayIcon::Information,
            2000
            );
    }
}
// 更新界面显示
void PomodoroTimer::updateDisplay()
{
    // 更新时间显示
    int minutes = remaining / 60;
    int seconds = remaining % 60;
    ui->lblTime->setText(
        QString("%1:%2")
            .arg(minutes, 2, 10, QLatin1Char('0'))
            .arg(seconds, 2, 10, QLatin1Char('0'))
        );

    // 更新状态显示
    QString status;
    switch(currentPhase) {
    case Work: status = "专注工作中"; break;
    case ShortBreak: status = "短休息中"; break;
    case LongBreak: status = "长休息中"; break;
    }
    ui->lblStatus->setText(status);

    // 更新统计信息
    ui->lblStats->setText(
        QString("总专注时间: %1 分钟\n完成番茄数: %2 个")
            .arg(totalMinutes)
            .arg(totalTomatoes)
        );

    // 更新日历标注
    QTextCharFormat format;
    format.setBackground(Qt::green);
    QMapIterator<QDate, int> it(dailyData);
    while (it.hasNext()) {
        it.next();
        if(it.value() > 0) {
            ui->calendar->setDateTextFormat(it.key(), format);
        }
    }
}
